package main

import (
	"database/sql"
	"log"
)

const sqlStmt = "CREATE TABLE channel (name text NOT NULL, url text NOT NULL, lastid text, PRIMARY KEY(name, url));"

func initDB() *sql.DB {
	db, err := sql.Open("sqlite3", "./channels.db")
	if err != nil {
		log.Fatal(err)
	}
	db.Exec(sqlStmt)
	return db
}

func insertChannels(db *sql.DB, channels *[]Channel) {
	tx, err := db.Begin()
	if err != nil {
		log.Fatal(err)
	}
	stmt, err := tx.Prepare(`INSERT INTO channel (name, url, lastid) VALUES(?, ?, "")`)
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()
	for _, channel := range *channels {
		_, err = stmt.Exec(channel.Name, channel.Url)
		if err != nil {
			continue
		}
	}
	tx.Commit()
}

func getLastID(db *sql.DB, channel *Channel) string {
	stmt, err := db.Prepare("SELECT lastid FROM channel WHERE name = ? AND url = ?")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()
	var id string
	err = stmt.QueryRow(channel.Name, channel.Url).Scan(&id)
	if err != nil {
		log.Fatal(err)
	}
	return id
}

func updateLastID(db *sql.DB, channel *Channel, id string) {
	_, err := db.Exec("UPDATE channel SET lastid = ? WHERE name = ? AND url = ?", id, channel.Name, channel.Url)
	if err != nil {
		log.Panicln(err.Error())
	}
}
